﻿using PersonaLibrary.Data;

namespace PersonaLibrary.ViewModel
{
    internal class LinqEditableItem<TEntity> : EditableItemViewModel<TEntity>
        where TEntity : BaseEntity
    {
        protected LinqToDbDataContext Context = new LinqToDbDataContext();

    	private bool _added;

		public override string Name
		{
			get
			{
				if (!_added)
				{
					EditableItem.PropertyChanged += delegate
					                                	{
					                                		RisePropertyChanged("Name");
					                                	};
					_added = true;
				}
				return EditableItem.FullName;
			}
		}

        public override void Commit()
        {
            if(EditableItem != null && EditableItem.Id == 0) 
				Context.GetTable<TEntity>().InsertOnSubmit(EditableItem);
            Context.SubmitChanges();
            base.Commit();
        }

		public override void Delete()
		{
			if (EditableItem != null)
				Context.GetTable<TEntity>().DeleteOnSubmit(EditableItem);
			Context.SubmitChanges();
			base.Delete();
		}

        public override void Dispose()
        {
            Context.Dispose();
        }

		public override string ToString()
		{
			return EditableItem.ToString();
		}
    }
}
